//
//  WBStatusListViewModel.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/15.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit
import SDWebImage

class WBStatusListViewModel: NSObject {
    
    /// 数据源数组
    var dataSourceArr: [WBStatusViewModel] = []
    
    func loadData (isPullDown: Bool, callBack: @escaping (Bool)->()) {
        //判断是否是首次加载数据， dataSource没东西，首次
        var since_id = "0"
        var max_id = "0"
        
        //在做下拉
        if isPullDown {
            let firstId = dataSourceArr.first?.statusModel.id
            since_id =  firstId ?? "0"
        } else {
            let lastId = dataSourceArr.last?.statusModel.id
            max_id = lastId ?? "0"
        }

        WBNetworkTool.shared.requestStatus(since_id: since_id, max_id: max_id) { (modelsArr) in
            
            if let modelArry = modelsArr as? [WBStatusModel] {
                //使用model创建viewModel
                var viewModelArr: [WBStatusViewModel] = []
                for model in modelArry {
                    let viewModel = WBStatusViewModel(statusModel: model)
                    viewModelArr.append(viewModel)
                }
                
                //根据是否是上下拉决定数据如何拼接
                if isPullDown {
                    //下拉时，将数据源拼在最新数据的后面
                    self.dataSourceArr = viewModelArr + self.dataSourceArr
                } else {
                    //上拉时，将最新数据拼在数据源的后面,但是会产生一条重复数据
                    if self.dataSourceArr.count > 0 {
                        //移除数据源中的最后一条数据
                        self.dataSourceArr.removeLast()
                    }
                    self.dataSourceArr += viewModelArr
                }
                
                //先将从服务器获取的数据中的单张图片先下载来
                
                self.downloadSingleImages(viewModelArr: viewModelArr, callBack: callBack)
            }
        }
    }
    
    func downloadSingleImages(viewModelArr:[WBStatusViewModel], callBack:@escaping (Bool)->()) {
        let group = DispatchGroup()
        
        for viewModel in viewModelArr {
            //说明该cell的是单张图片
            if let picUrls = viewModel.picUrls,  picUrls.count == 1{
                //入组
                group.enter()
                let url = URL(string: picUrls[0].middle_pic!)
//                SDWebImageManager.shared.loadImage(with: url, options: [], progress: nil) { (<#UIImage?#>, <#Data?#>, <#Error?#>, <#SDImageCacheType#>, <#Bool#>, <#URL?#>) in
//                    <#code#>
//                }
                //SDWebImageManager.shared.imageDownloader?.downloadImage(with: url, options:
                SDWebImageManager.shared.loadImage(with: url, options: [], progress: nil, completed: { (downloadImage, _, _, _,_,_)  in
                    //拿到单张图片
                    if let downloadImage = downloadImage {
                        var size = downloadImage.size //老的宽， 老的高
                        
                        //对过宽和过窄做一个处理
                        let maxWidth: CGFloat = 300.0 //新宽
                        let maxHeight: CGFloat = 400.0 //新的高
                        
                        //对过宽的图片的处理
                        if size.width > maxWidth {
                            //新宽/新高=老宽/老高
                            let newHeigh = size.height * 300 / size.width
                            size.width = maxWidth
                            size.height = newHeigh
                        }
                        
                        viewModel.pictureSize = size
                        print("\(viewModel.statusModel.user?.screen_name):\(size)")
                        //出组
                        group.leave()
                    }
                })
            }
        }
        
        group.notify(queue: DispatchQueue.main) {
            callBack(true)
        }
    }
}
